﻿using CK.Sprite.Framework;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Quartz;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace CK.Sprite.JobCore
{
    public abstract class BaseCallJob : DomainService
    {
        protected async Task DoExecute(IJobExecutionContext context, Func<Task> jobExecFunc)
        {
            JobExecLog jobExecLog = null;
            JobConfig jobConfig = null;
            try
            {
                var jobConfigId = Guid.Parse(context.JobDetail.JobDataMap.GetString("JobConfigId"));

                jobConfig = await _serviceProvider.DoDapperServiceAsync(DefaultDbConfig, async (unitOfWork) =>
                {
                    var jobConfigRepository = new GuidRepositoryBase<JobConfig>(unitOfWork);
                    var tempJobConfig = await jobConfigRepository.GetAsync(jobConfigId);
                    return tempJobConfig;
                });

                if (jobConfig != null)
                {
                    jobExecLog = new JobExecLog()
                    {
                        Id = Guid.NewGuid(),
                        JobConfigId = jobConfig.Id,
                        Description = jobConfig.Description,
                        ExecStartTime = DateTime.Now,
                        ExecLocation = jobConfig.ExecLocation,
                        JobExecType = jobConfig.JobExecType,
                        JobGroup = jobConfig.JobGroup,
                        TriggerType = jobConfig.TriggerType,
                        JobName = jobConfig.JobName,
                        Params = jobConfig.Params,
                        ExecType = EExecType.执行中
                    };

                    await _serviceProvider.DoDapperServiceAsync(DefaultDbConfig, async (unitOfWork) =>
                    {
                        var jobExecLogRepository = new GuidRepositoryBase<JobExecLog>(unitOfWork);
                        await jobExecLogRepository.InsertAsync(jobExecLog);
                    });
                }

                await jobExecFunc();

                if (jobConfig != null)
                {
                    var nowTime = DateTime.Now;
                    await _serviceProvider.DoDapperServiceAsync(DefaultDbConfig, async (unitOfWork) =>
                    {
                        var jobExecLogRepository = new GuidRepositoryBase<JobExecLog>(unitOfWork);
                        var dbExecLog = await jobExecLogRepository.GetAsync(jobExecLog.Id);
                        dbExecLog.ExecEndTime = nowTime;
                        dbExecLog.ExecDuration = (nowTime - dbExecLog.ExecStartTime).TotalSeconds;
                        dbExecLog.ExecType = EExecType.执行成功;
                        await jobExecLogRepository.UpdateAsync(dbExecLog);
                    });
                }
            }
            catch (Exception ex)
            {
                if (jobConfig != null)
                {
                    var nowTime = DateTime.Now;
                    await _serviceProvider.DoDapperServiceAsync(DefaultDbConfig, async (unitOfWork) =>
                    {
                        var jobExecLogRepository = new GuidRepositoryBase<JobExecLog>(unitOfWork);
                        var dbExecLog = await jobExecLogRepository.GetAsync(jobExecLog.Id);
                        dbExecLog.ExecEndTime = nowTime;
                        dbExecLog.ExecDuration = (nowTime - dbExecLog.ExecStartTime).TotalSeconds;
                        dbExecLog.ExecType = EExecType.执行失败;
                        dbExecLog.ExecMsg = $"{ex.Message}。{ex.StackTrace}";
                        await jobExecLogRepository.UpdateAsync(dbExecLog);
                    });
                }
                    
            }
        }
    }
}
